﻿using System;
using System.Windows.Forms;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YJKExcelFormTool.DataDefine;
using YJKExcelFormTool.Forms;
using YJKExcelFormTool.Kits;

namespace YJKExcelFormTool.Designer
{
	internal class GraphPaperDirectoryDesigner
	{
		public GraphPaperDirectoryDesigner(ExternalCommandData cmdData)
		{
			this.m_Revit = cmdData;
		}

		public Result Execute(ref string message)
		{
			using (GraphPaperDirectoryForm graphPaperDirectoryForm = new GraphPaperDirectoryForm(this.m_Revit))
			{
				if (graphPaperDirectoryForm.ShowDialog() == DialogResult.OK)
				{
					if (graphPaperDirectoryForm.IsDrawingToRevit)
					{
						return this.Drawing(ref message, graphPaperDirectoryForm.TheTableInfos);
					}
					return this.Export(ref message, graphPaperDirectoryForm.TheTableInfos, graphPaperDirectoryForm.ExportKit);
				}
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private Result Drawing(ref string message, TableInfos tableInfos)
		{
			if (new ViewControler(this.m_Revit, ViewControler.TableViewType.TVT_GRAPHPAPERDIRECTORY).CreateDraftingView(100) == ViewSelectResult.VSR_Cancel)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			TableDrawingToRevitKit tableDrawingToRevitKit = new TableDrawingToRevitKit(this.m_Revit, tableInfos, null);
			try
			{
				tableDrawingToRevitKit.Drawing(true);
			}
			catch
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private Result Export(ref string message, TableInfos tableInfos, TableExportKit exportKit)
		{
			Transaction transaction = new Transaction(this.m_Revit.Application.ActiveUIDocument.Document);
			transaction.Start("Export table");
			try
			{
				exportKit.ExportToExcel();
				transaction.Commit();
			}
			catch
			{
				if (transaction != null)
				{
					transaction.RollBack();
				}
				return Autodesk.Revit.UI.Result.Failed;
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private ExternalCommandData m_Revit;
	}
}
